
function ReadPaper(){
    var _this = this;
    //学员的考试编号
    var examNoList = [];
    var examStrategy ;
    var questionIdList = [];

    //当前试题Id
    var questionId ;
    var nowQuestionId;
    //当前试题类型
    var chrType ;
    //根据试题Id用户Id查出的所有答案
    var answerResults;

    var questionAnswerMap;

    var tishiMsg="";


    _this.init = function () {
        // 是否有人 线上正式考试
        $.ajax({
             url: appPath + '/readPaper/projectExamUserCount',
             async: false,
             type: 'post',
             data: {'projectId':$("#projectId").val(), 'examStatus':'2,3'},
             success: function (data) {
                 if(data.code != 10000){
                     layer.msg(data.message);
                     window.close();
                     return;
                 }
                 if(undefined != data.result ){
                     var result = data.result;
                     examNoList = result.examNoList;

                     //获取所有主观题
                     _this.getAllsubQues();
                 }else{
                     layer.msg("暂无学员考试！");
                     window.close();
                     return;
                 }
             }
         });
    };

    _this.initEvent = function(){
        // 点击返回主页
        $("#btn_back").bind("click", function () {
            _this.saveExamScore();
            window.close();
        });
    }


    /**
     * 获取所有主观题
     */
    _this.getAllsubQues = function(){
        //根据项目取出主观题分值
        // 根据考试编号取出所有 主观题/答案/学员答案
        $.ajax({
            url: appPath + '/readPaper/getQuestions',
            async: false,
            type: 'post',
            data: {'projectId':$("#projectId").val(), 'examNos':examNoList.join(",")},
            success: function (data) {
                if(data.code != 10000){
                    layer.msg(data.message);
                }
                var result = data.result;
                //题型分值
                examStrategy = result.examStrategy;
                questionAnswerMap = result.questionAnswerMap;
                //主观题
                var questions = result.questions;
                if(questions != undefined && questions.length > 0){
                    _this.addQuestions(questions);
                }
            }
        });
    };


    /**
     * 填充左侧试题列表
     * @param questions
     */
    _this.addQuestions = function (questions) {
        var html = "";
        for(var i=0; i< questions.length; i++){
            var question = questions[i];
            //所有主观题Id
            questionIdList.push(question.intId);
            //试题类型（填空，论述，简答，计算，绘图）
            chrType = question.chrType;
            html += '<li id="liques'+question.intId+'" questionId="'+question.intId+'" varAnswer="'+question.varAnswer+'" content="'+question.varContent+'" qType="'+chrType+'" onclick="readPapers.liChange(this)" varImgAnswer="';
            if(chrType != '04'){
                html += question.varAnswerImages;
            }
            html += '"';
            //是否阅卷完毕
            var answers = questionAnswerMap[question.intId];
            if(null == answers){
                continue;
            }
            var allPaper = answers.length;
            var readPaper = 0;
            var saveScore = 0;
            for (var j=0;j<answers.length;j++){
                if(undefined != answers[j].if_readPaper){
                    if(Number(answers[j].if_readPaper) == 2){
                        saveScore++;
                    }
                    readPaper++;
                }
            }
            html += 'allPaper="'+allPaper+'" readPaper="'+readPaper+'"';

            if(allPaper == readPaper){
                html += ' style="background-color:#8d7bf966;';

            }
            if(saveScore == allPaper){
                html += 'color:#999;';
            }
            html += '"';

            //默认加载第一题答案
            if(i == 0){
                if(allPaper != readPaper){
                    html += ' class="li-bgcolor"';
                }
                //缓存当前试题Id
                questionId = question.intId;
                // 题目，答案，参考答案
                if(chrType != '04'){
                    _this.questionAndAnswer(question.varContent, question.varAnswer, question.varAnswerImages);
                }else{
                    _this.questionAndAnswer(question.varContent, question.varAnswer, '');
                }
            }
            html += '>'+(i+1)+'.'+question.varContent+'</li>';
        }
        $(".questionUl").html(html);
    };



    /**
     * li点击切换
     * @param obj
     */
    _this.liChange = function (obj) {
        if(_this.checkInputScore()){
            //保存当前分值
            if($("#score").val() != '' && Number(answerResults[Number($("#before").attr("nowIndex"))].if_readPaper) != 2){
                nowQuestionId = questionId;
                _this.saveStudentScore();
            }
            // 清空 当前答案的试卷编号
            $("#nowExanNo").val("");
            $("#before").attr("nowIndex", 0);
            $("#after").attr("nowIndex", 0);

            questionId = $(obj).attr("questionId");

            chrType = $(obj).attr("qType");
            var content = $(obj).attr("content");
            var varAnswer = $(obj).attr("varAnswer");
            var varImgAnswer = $(obj).attr("varImgAnswer");
            //填充右侧 题目，答案，参考答案
            _this.questionAndAnswer(content, varAnswer, varImgAnswer);
            // 切换li选中效果
            $(obj).addClass('li-bgcolor').css("font-size","20px").siblings('li').css("font-size","16px").removeClass('li-bgcolor');
        }
    };


    /**
     * 填充右侧 题目，答案，参考答案
     * @param chrType   试题类型
     * @param content   题目
     * @param varAnswer 参考答案
     * @param imgAnswer 解析图片
     */
    _this.questionAndAnswer = function (content, varAnswer, imgAnswer) {
        var score = 0;
        if(chrType == '04'){
            score = examStrategy.filloutScore;
        }else if(chrType == '05'){
            score = examStrategy.quesAnsScore;
        }else if(chrType == '06'){
            score = examStrategy.discussScore;
        }else if(chrType == '07'){
            score = examStrategy.analyseScore;
        }else if(chrType == '08'){
            score = examStrategy.drawingScore;
        }
        if(imgAnswer != ''){
            $("#imgAnswer").show().find('img').attr("src", imgAnswer).attr("data-original", imgAnswer);
        }else{
            $("#imgAnswer").hide();
        }
        $("#questionScore").html(score);
        $("#questionStr").html(content);
        $("#answer").html(varAnswer);

        //学员答案
        _this.getStudentAnswer();
    };


    /**
     * 点击上一个、下一个学员
     * @param obj
     */
    _this.changeStudent = function (idName) {
        if(_this.checkInputScore()){
            tishiMsg = "";
            //保存当前分值
            if($("#score").val() != '' && Number(answerResults[Number($("#before").attr("nowIndex"))].if_readPaper) != 2){
                nowQuestionId = questionId;
                _this.saveStudentScore();
            }
            //第几个学员（默认第一个学员）
            var nowIndex = $("#"+idName).attr("nowIndex");

            // 点击上一个学员
            if(idName == 'before'){
                if(Number(nowIndex) == 0){
                    if(tishiMsg == ""){
                        layer.msg("已经是第一个学员");
                    }
                    return;
                }
                nowIndex = Number(nowIndex) -1;

                // 点击下一个学员
            }else{
                if(Number(nowIndex) == answerResults.length-1){
                    if(tishiMsg == ""){
                        layer.msg("已经是最后一个学员");
                    }
                    return;
                }
                nowIndex = Number(nowIndex)+1;
            }
            $("#before").attr("nowIndex", nowIndex);
            $("#after").attr("nowIndex", nowIndex);
            // 清空 当前答案的试卷编号
            $("#nowExanNo").val("");

            //学员答案
            _this.getStudentAnswer();
        }
    };


    /**
     * 获取学员答案
     */
    _this.getStudentAnswer = function () {

        //当前试题所有学员答案list
        answerResults = questionAnswerMap[questionId+''];
        if(answerResults){
        var answer = answerResults[Number($("#before").attr("nowIndex"))];

        //解析学员答案
        _this.nowStudentAnswer(answer);
        }else {
            layer.msg("无该题的答案");
            return;
        }
    };


    /**
     * 填充当前学员答案
     * @param answerResult
     */
    _this.nowStudentAnswer = function (answerResult) {
        var answer = '';
        var imgAnswer = '';

        if(chrType != '04'){
            var answers = (answerResult.answer).split("&&");
            //答案包含文字，图片
            if(answers.length > 1){
                answer = answers[0];
                imgAnswer = answers[1];
            }else{
                //仅图片
                if(answers[0].indexOf("http") != -1 && answers[0].indexOf("play.do") != -1){
                    imgAnswer = answers[0];
                }else{
                    answer = answers[0]
                }
            }
        }else{
            answer = answerResult.answer;
        }

        //填充学员答案
        $("#studentAnswer").html(answer);
        if(imgAnswer != ''){
            $("#studentImgAnswer").attr("src", imgAnswer).attr("data-original", imgAnswer).show();
            $("#rotateImg").show();
        }else{
            $("#studentImgAnswer").hide();
            //$("#rotateImg").hide();
        }
        // 学员Id, 试卷编号， 是否阅卷
        $("#nowUserId").val(answerResult.user_id);
        $("#nowExanNo").val(answerResult.exam_no);
        $("#nowRead").val(answerResult.if_readPaper == undefined ? "0" : answerResult.if_readPaper);
        //已阅卷显示得分，为阅卷得分为空
        if(answerResult.if_readPaper != undefined){
            $("#score").val(answerResult.score).removeAttr("disabled");
            if(Number(answerResult.if_readPaper) == 2){
                $("#score").attr("disabled", "disabled");
            }
        }else{
            $("#score").val("").removeAttr("disabled");
        }
    };


    /**
     * 检查input框分值是否符合
     */
    _this.checkInputScore = function () {
        // 试题分值
        var questionScore = Number($("#questionScore").html());
        var inputScore = $("#score").val();
        if('' != inputScore){
            if(Number(inputScore) > questionScore){
                layer.msg("所得分数不得超过试题标准分！");
                $("#score").val("");
                return false;
            }
        }else{
            // layer.msg("请给学员打分！");
            // return false;
        }
        return true;
    };


    /**
     * 保存分值
     */
    _this.saveStudentScore = function () {

        var isCorrect = 1;      //是否正确(1:是；2:否)
        if(Number($("#score").val()) < Number($("#questionScore").html())){
            isCorrect = 2;
        }
        var param = {
            'userId' : $("#nowUserId").val(),
            'examNo' : $("#nowExanNo").val(),
            'questionId' : questionId,
            'projectId' : $("#projectId").val(),
            'score' : $("#score").val(),
            'isCorrect' : isCorrect
        };
        $.ajax({
            url: appPath + '/readPaper/saveStudentScore',
            async: false,
            type: 'post',
            data: param,
            success: function (data) {
                if (data.code != 10000) {
                    layer.msg(data.message);
                    return;
                }
                var answerList = questionAnswerMap[questionId+''];
                answerResults[Number($("#before").attr("nowIndex"))]['score'] = $("#score").val();
                answerList[Number($("#before").attr("nowIndex"))]['score'] = $("#score").val();

                var allpaper = $("#liques"+questionId).attr("allpaper");

                //当前学员试题未阅卷，阅卷数量+1 ; 控制li背景色（当前试题所有学员阅卷完毕变色）
                if($("#nowRead").val() == '0'){
                    var readpaper = $("#liques"+questionId).attr("readpaper");
                    $("#liques"+questionId).attr("readpaper", Number(readpaper)+1);
                    if(Number(readpaper)+1 == allpaper){
                        $("#liques"+questionId).css("background-color", "#8d7bf966");
                    }
                    answerResults[Number($("#before").attr("nowIndex"))]['if_readPaper'] = "1";
                    answerList[Number($("#before").attr("nowIndex"))]['if_readPaper'] = "1";
                    $("#nowRead").val("1");
                }
                var readpaper = $("#liques"+questionId).attr("readpaper");

                //提示是否保存，得分不可修改
                if(Number(allpaper) == Number(readpaper) && $("#liques"+questionId).attr("saveRead") == undefined){
                    tishiMsg = "1";
                    layer.confirm('是否确认当前试题各学员得分？一旦确认将无法修改。', {
                        icon : 3,
                        btn: ['确定','取消']        //按钮
                    }, function(index){
                        param = {
                            'examNos' : examNoList.join(","),
                            'questionId' : nowQuestionId,
                            'projectId' : $("#projectId").val()
                        };
                        $.ajax({
                            url: appPath + '/readPaper/saveStudentScoreStatus',
                            async: false,
                            type: 'post',
                            data: param,
                            success: function (data) {
                                layer.close(index);
                                //标识是否确认保存分值，不可修改
                                $("#score").attr("disabled", "disabled");
                                for(var i=0;i<questionAnswerMap[nowQuestionId+''].length;i++){
                                    questionAnswerMap[nowQuestionId+''][i]['if_readPaper'] = 2;
                                }
                                answerResults = questionAnswerMap[nowQuestionId+''];
                                $("#liques"+nowQuestionId).css("color","#999");
                            }
                        });
                    }, function(index){
                        //取消
                        layer.close(index);
                    });
                }
            }
        });
    };


    /**
     * 关闭页面，保存主观题分数
     */
    _this.saveExamScore = function () {
        // project_statistics_info, exam_score
        //保存当前分值(防止输入完得分后直接关闭浏览器导致分数未保存)
        if($("#score").val() != '' && Number(answerResults[Number($("#before").attr("nowIndex"))].if_readPaper) != 2){
            if(_this.checkInputScore()){
                _this.saveStudentScore();
            }
        }

        var param = {
            'examNos' : examNoList.join(","),
            'projectId' : $("#projectId").val(),
            'questionIds' : questionIdList.join(",")
        };
        $.ajax({
            url: appPath + '/readPaper/saveSubjectiveScore',
            async: true,
            type: 'post',
            data: param,
            success: function (data) {
            }
        });
    }


};


var readPapers = new ReadPaper();